package com.cyj.springbootservice.service.impl;


import com.cyj.springbootservice.service.SmsService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @description:
 * @Author C_Y_J
 * @create 2021-03-22 10:30
 **/
@Service
public class SmsServiceImpl implements SmsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SmsService.class);

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    public static final String REDIS_KEY_PREFIX = "CHECK_CODE_";

    @Override
    public Map<String, Object> sendCheckCode(String mobile) {
        Map<String, Object> result = new HashMap<>(2);

        try {
            // 通过手机号码查询，用户上一次发送的验证码是否失效
            String redisKey = REDIS_KEY_PREFIX + mobile;
            String value = this.redisTemplate.opsForValue().get(redisKey);
            if (!StringUtils.isEmpty(value)) {
                result.put("code", 1);
                result.put("msg", "上一次发送的验证码还未失效");
                return result;
            }
            // 发送短信
//            String code = this.sendSms(mobile);
            String code = "123456";
            if (StringUtils.isEmpty(code)) {
                result.put("code", 2);
                result.put("msg", "发送短信验证码失败");
                return result;
            }
            // 将验证码存储到Redis,2分钟后失效
            this.redisTemplate.opsForValue().set(redisKey, code, Duration.ofMinutes(2));

            // 发送验证码成功
            result.put("code", 3);
            result.put("msg", "ok");
            return result;
        } catch (Exception e) {
            LOGGER.error("发送验证码出错！" + mobile, e);
            result.put("code", 4);
            result.put("msg", "发送验证码出现异常");
            return result;
        }

    }

    @Override
    public Boolean checkVerificationCode(String phone, String code) {
        String redisKey = REDIS_KEY_PREFIX + phone;
        String value = this.redisTemplate.opsForValue().get(redisKey);

        if (Objects.requireNonNull(value).equals(code)) {
            //验证码正确
            this.redisTemplate.delete(redisKey);
            return true;
        }
        return false;
    }

    public String sendSms(String mobile) {

        //短信服务商的请求路径
        String url = "https://open.ucpaas.com/ol/sms/sendsms";
        // 1. 封装参数
        Map<String, Object> params = new HashMap<>();
        params.put("sid", "56f6523e8f50c85fe92d5d12a8dabd6f");
        params.put("token", "41fabadd9a221ab4a439548b4dc88433");
        params.put("appid", "dd7d74e604284a6b9cc668c6591c84c7");
        params.put("templateid", "487656");
        params.put("mobile", mobile);
        //生成6位数验证
        params.put("param", RandomUtils.nextInt(100000, 999999));

        //2. 使用restTemplate 把参数传递给短信服务商，让短信服务商发送短信
        ResponseEntity<String> stringResponseEntity = this.restTemplate.postForEntity(url, params, String.class);

        //3. 将body序列化为json数据
        try {
            JsonNode jsonNode = MAPPER.readTree(stringResponseEntity.getBody());
            //4. 查看短信服务商的开发文档 根据返回的结果判断是否发送成功
            //000000 表示发送成功
            if ("000000".equals(jsonNode.get("code").textValue())) {
                return String.valueOf(params.get("param"));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
